/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "modifier/rs_extended_modifier.h"

#include <memory>

#include "modifier/rs_modifier_type.h"
#include "modifier/rs_render_modifier.h"
#include "pipeline/rs_node_map.h"
#include "pipeline/rs_recording_canvas.h"
#include "platform/common/rs_log.h"

namespace OHOS {
namespace Rosen {
RSDrawingContext RSExtendedModifierHelper::CreateDrawingContext(std::weak_ptr<RSCanvasNode> canvasnode)
{
    auto node = canvasnode.lock();
    if (!node) {
        RS_LOGW("RSExtendedModifierHelper::CreateDrawingContext node is nullptr");
        return { nullptr };
    }
    auto recordingCanvas = new ExtendRecordingCanvas(node->GetPaintWidth(), node->GetPaintHeight());
    recordingCanvas->SetIsCustomTextType(node->GetIsCustomTextType());
    recordingCanvas->SetIsCustomTypeface(node->GetIsCustomTypeface());
    return { recordingCanvas, node->GetPaintWidth(), node->GetPaintHeight() };
}

std::shared_ptr<RSRenderModifier> RSExtendedModifierHelper::CreateRenderModifier(
    RSDrawingContext& ctx, PropertyId id, RSModifierType type, int16_t index)
{
    auto renderProperty = std::make_shared<RSRenderProperty<Drawing::DrawCmdListPtr>>(
        RSExtendedModifierHelper::FinishDrawing(ctx), id);
    auto renderModifier =  std::make_shared<RSDrawCmdListRenderModifier>(renderProperty);
    renderModifier->SetType(type);
    renderModifier->SetIndex(index);
    return renderModifier;
}

std::shared_ptr<Drawing::DrawCmdList> RSExtendedModifierHelper::FinishDrawing(RSDrawingContext& ctx)
{
    auto recordingCanvas = static_cast<ExtendRecordingCanvas*>(ctx.canvas);
    if (!recordingCanvas) {
        RS_LOGW("RSExtendedModifierHelper::FinishDrawing recordingCanvas is nullptr");
        return nullptr;
    }
    auto recording = recordingCanvas->GetDrawCmdList();
    if (!recording) {
        RS_LOGW("RSExtendedModifierHelper::FinishDrawing recording is nullptr");
        delete ctx.canvas;
        ctx.canvas = nullptr;
        return nullptr;
    }
    if (RSSystemProperties::GetDrawTextAsBitmap()) {
        // replace drawOpItem with cached one (generated by CPU)
        recording->GenerateCache();
    }
    delete ctx.canvas;
    ctx.canvas = nullptr;
    return recording;
}
} // namespace Rosen
} // namespace OHOS
